<?php
header('Content-Type: application/json; charset=utf-8');

// 引入数据库配置
$dbConfig = include('db_config.php');

try {
    // 创建数据库连接
    $dsn = "mysql:host=" . $dbConfig['host'] . ";dbname=" . $dbConfig['dbname'] . ";charset=" . $dbConfig['charset'];
    $pdo = new PDO($dsn, $dbConfig['username'], $dbConfig['password']);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // 查询 SQL，过滤非法值并按获赞数量降序排序
    $stmt = $pdo->prepare("SELECT * FROM mi_file 
        WHERE 获赞数量 REGEXP '^[0-9]+$' 
        ORDER BY CAST(获赞数量 AS UNSIGNED) DESC");
    $stmt->execute();

    // 获取查询结果
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // 返回结果
    if (empty($results)) {
        throw new Exception("未找到任何有效数据！");
    }

    echo json_encode(['status' => 'success', 'message' => '成功', 'data' => $results], JSON_UNESCAPED_UNICODE);

} catch (PDOException $e) {
    $errorResult = [
        'status' => 'error',
        'message' => '数据库操作失败：' . $e->getMessage()
    ];
    echo json_encode($errorResult, JSON_UNESCAPED_UNICODE);
} catch (Exception $e) {
    $errorResult = [
        'status' => 'error',
        'message' => $e->getMessage()
    ];
    echo json_encode($errorResult, JSON_UNESCAPED_UNICODE);
}
